/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.documents.service.document;

import com.documents.common.core.PageBean;
import com.documents.common.core.service.BaseSrv;
import com.documents.pojo.DocTypeAndGroup;
import com.documents.pojo.DocumentGroup;
import com.documents.pojo.DocumentType;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
//import net.sf.json.JSONException;
import java.util.Set;
import org.apache.commons.collections.map.ListOrderedMap;

/**
 *
 * @author Administrator
 */
public class DocumentTypeService extends BaseSrv<DocumentType, Integer> {

    private DocumentGroupService documentGroupService;

    public DocumentGroupService getDocumentGroupService() {
        return documentGroupService;
    }

    public void setDocumentGroupService(DocumentGroupService documentGroupService) {
        this.documentGroupService = documentGroupService;
    }

    public PageBean getPageBean(int page, int pageSize, DocumentType cat) {
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(page);
        String condition = "";
        Object[] parameters = new Object[1];
        int paramIndex = 0;
        if (cat != null) {

            if (cat.getPid() >= 0) {
                condition += "pid=?";
                parameters[paramIndex] = cat.getPid();
                paramIndex++;
            }

            Long allRow = this.findTotalCount(condition, parameters);
            int totalPage = PageBean.countTotalPage(pageSize, allRow.intValue()); // 总页数
            pageBean.setAllRow(allRow.intValue());
            pageBean.setTotalPage(totalPage);
            List<DocumentType> list;
            if (page == 1) {
                list = this.findWithPaging(condition, parameters, "userCode", page - 1, pageSize);
            } else {
                list = this.findWithPaging(condition, parameters, "userCode", (page - 1) * pageSize, pageSize);
            }
            List<DocTypeAndGroup> tglist = new ArrayList();
            for (DocumentType dType : list) {
                String sql = "select name from document_group where id in(select groupid from group_type where typeid=" + dType.getId() + ")";
                List groupNames = this.jdbcTemplate.queryForList(sql);
                String names = "";
                for (int i = 0; i < groupNames.size(); i++) {
                    ListOrderedMap map = (ListOrderedMap) groupNames.get(i);
                    String name = (String) map.get("name");
                    if (i == 0) {
                        names = name;
                    } else {
                        names = names + "," + name;
                    }
                }
                DocTypeAndGroup typeGroup = new DocTypeAndGroup();
                typeGroup.setCode(dType.getCode());
                typeGroup.setDes(dType.getDes());
                typeGroup.setId(dType.getId());
                typeGroup.setPid(dType.getPid());
                typeGroup.setName(dType.getName());
                typeGroup.setUserCode(dType.getUserCode());
                typeGroup.setGroupName(names);
                tglist.add(typeGroup);
            }
            pageBean.setList(tglist);

        } else {
            Long allRow = this.findTotalCount("", null);
            int totalPage = PageBean.countTotalPage(pageSize, allRow.intValue()); // 总页数
            pageBean.setAllRow(allRow.intValue());
            pageBean.setTotalPage(totalPage);
            List<DocumentType> list;
            if (page == 1) {
                list = this.findWithPaging(condition, parameters, "userCode", page - 1, pageSize);
            } else {
                list = this.findWithPaging(condition, parameters, "userCode", (page - 1) * pageSize, pageSize);
            }
            List<DocTypeAndGroup> tglist = new ArrayList();
            for (DocumentType dType : list) {
                String sql = "select name from document_group where id in(select groupid from group_type where typeid=" + dType.getId() + ")";
                List groupNames = this.jdbcTemplate.queryForList(sql);
                String names = "";
                for (int i = 0; i < groupNames.size(); i++) {
                    ListOrderedMap map = (ListOrderedMap) groupNames.get(i);
                    String name = (String) map.get("name");
                    if (i == 0) {
                        names = name;
                    } else {
                        names = names + "," + name;
                    }
                }
                DocTypeAndGroup typeGroup = new DocTypeAndGroup();
                typeGroup.setCode(dType.getCode());
                typeGroup.setDes(dType.getDes());
                typeGroup.setId(dType.getId());
                typeGroup.setPid(dType.getPid());
                typeGroup.setName(dType.getName());
                typeGroup.setUserCode(dType.getUserCode());
                typeGroup.setGroupName(names);
                tglist.add(typeGroup);
            }
            pageBean.setList(tglist);
        }
        return pageBean;
    }

    public void doTypeWhile(int groupid, List<DocumentType> list) {
        List<DocumentGroup> findList = documentGroupService.find("pid=?", new Object[groupid], "id");
        if (!findList.isEmpty()) {
            for (DocumentGroup g : findList) {
                this.getTypeByGroupId(g.getId());
            }

        } else {
            DocumentGroup findUnique = documentGroupService.findUnique("id=?", new Object[groupid]);
            Set<DocumentType> typelist = findUnique.getDocumentTypes();
            if (typelist.isEmpty()) {
                list.addAll(typelist);
            }
        }
    }

    public List<DocumentType> getTypeByGroupId(int groupid) {

        List<DocumentType> totleList = new ArrayList<DocumentType>();
        doTypeWhile(groupid, totleList);


        return totleList;
    }
//
//    public JSONArray getAllJSONArray() {
//        List<DocumentType> grouplist = this.findAll();
//        JSONArray jsonArrayTemp = new JSONArray();
//        for (DocumentType s : grouplist) {
//
//            JSONObject jsonTemp = new JSONObject();
//            try {
//                jsonTemp.put("id", s.getId());
//                jsonTemp.put("pId", s.getPid());
//                jsonTemp.put("name", s.getName());
//                jsonTemp.put("des", s.getDes());
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//            jsonArrayTemp.put(jsonTemp);
//        }
//        return jsonArrayTemp;
//    }

    /*
     * 生成部门编码,使用三位编码，如:001002
     */
    @SuppressWarnings("unchecked")
    private String generateCode(DocumentType parent) {
        List<DocumentType> groups = null;
//        ?this.findUnique("objid=?", new Object[]{obj_id});
        groups = this.dao.find("pid=?", new Object[]{parent.getId()}, "id");
        if (groups == null || groups.isEmpty()) {//不存在兄弟
            if (null == parent) {//父亲也为空的话，代表第一次添加
                return "001";
            } else {
                return parent.getCode() + "001";
            }
        }
        String code = "";
        //
        DocumentType max = groups.get(0);
        int maxCode = 0;
        for (DocumentType group : groups) {
            int currCode = Integer.valueOf(group.getCode().substring(group.getCode().length() - 3, group.getCode().length()));
            if (currCode > maxCode) {
                maxCode = currCode;
            }
        }
        if (String.valueOf(max.getCode()).length() == 3) {
            code = valueOf(String.valueOf(maxCode + 1));
        } else {
            code = max.getCode().substring(0, max.getCode().length() - 3) + valueOf(String.valueOf(maxCode + 1));
        }
        return code;
    }

    private String valueOf(String str) {
        if (str == null || str.isEmpty()) {
            return "000";
        }
        try {
            int code = Integer.valueOf(str);
            if (code < 10 && code > 0) {
                return "00" + code;
            }
            if (code < 100 && code >= 10) {
                return "0" + code;
            } else {
                return String.valueOf(code);
            }
        } catch (Exception e) {
            return "000";
        }
    }

    public DocumentType saveInstance(DocumentType type, DocumentGroup property) {
        DocumentType pp = this.findUnique("id=?", new Object[]{type.getPid()});
        Set groupList = new HashSet();
        groupList.add(property);
        type.setDocumentGroups(groupList);
        type.setCode(this.generateCode(pp));
        type.setPid(type.getPid());
        this.save(type);

        return type;
    }

    public void deleteById(Integer documentCatId) {
        DocumentType documentCat = null;
        documentCat = this.findUnique("id=?", new Object[]{documentCatId});

        if (documentCat != null) {
            String code = documentCat.getCode();
            String cString = code + "%";

            List<DocumentType> list = this.find("code like ?", new Object[]{cString}, "id");


            for (DocumentType d : list) {
                this.delete(d);
            }
        }
    }
}
